home *** CD-ROM | disk | FTP | other *** search
/ Language/OS - Multiplatform Resource Library / LANGUAGE OS.iso / smaltalk / stv.lha / STV / ISA / artifact / timer.cls < prev   
Text File  |  1993-07-23  |  2KB  |  89 lines

  1.  
  2. " Performance Timer (From Smalltalk/V Course)
  3.   By Tom Wrensch & Gene Korienek
  4.  
  5.   Here's a simple alternative to the millisecondsToRun:
  6.   message in Time.  This timer works like a simple stop
  7.   watch & can be used to time multiple events.  The
  8.   only problem with it is the same as the problem with
  9.   millisecondsToRun: - the time is only accurate to
  10.   1/18th of a second on DOS machines and 1/60th of a
  11.   second on Macs (I believe the number is 1/30th of a
  12.   second for OS/2-PM).
  13.  
  14.   To time a piece of code just do this:
  15.  
  16.     | timer |
  17.     timer := Timer new.
  18.     timer start.
  19.     1000 timesRepeat: [10 factorial].
  20.     timer stop.
  21.     timer totalTime
  22.  
  23.   The timer can also be used to time multiple events:
  24.  
  25.     | timer |
  26.     timer :=  Timer new.
  27.     timer start.
  28.     1000 timesRepeat: [10 factorial].
  29.     timer stop.
  30.     timer time: [Smalltalk unusedMemory].
  31.     timer totalTime.
  32.  
  33.   Remember the limitation on the timing resolution."!
  34.     
  35.  
  36.  
  37. Object subclass: #Timer
  38.   instanceVariableNames: 
  39.     'total events start '
  40.   classVariableNames: ''
  41.   poolDictionaries: '' !
  42.  
  43. !Timer class methods !
  44.  
  45. new
  46.     "Answer an initialized instance"
  47. ^super new initialize! !
  48.  
  49.  
  50. !Timer methods !
  51.  
  52. averageTime
  53.     "Answer the average time for all events."
  54. ^total // events!
  55.  
  56. initialize
  57.     "Private - Initialize the instance variables."
  58. total := 0.
  59. events := 0.
  60. start := nil.!
  61.  
  62. start
  63.     "Start timing an event."  
  64. start := Time millisecondClockValue.!
  65.  
  66. stop
  67.     "Stop timing an event."
  68. | end |
  69. end := Time millisecondClockValue.
  70. end < start
  71.     ifTrue: [end := end + (24 * 3600)].
  72. total := total + (end - start).
  73. events := events + 1.!
  74.  
  75. time: aBlock
  76.     "Execute aBlock as a timed event."
  77. self start.
  78. aBlock value.
  79. self stop.!
  80.  
  81. totalTime
  82.     "Answer the total time for all events."
  83. ^total! !
  84.  
  85.  
  86.  
  87.  
  88.  
  89.